import { Platform } from 'react-native';
import { baseURL, } from '!/app.json'
import { uploadImgApi } from '~/api/upload';
import { Storage, RecordKeys } from "~/store";


// 上传音频
export async function uploadAudio(path: string) {
    const realPath = Platform.OS === 'ios' ? path.replace('file://', '') : path;
    const formData = new FormData();
    formData.append('video', {
        uri: Platform.OS === 'ios' ? path : 'file://' + realPath,
        name: 'audio.mp4',
        type: 'audio/mp4',
    } as any);
    try {
        const response = await fetch(baseURL + "weixin/upload/audio", {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            body: formData,
        });

        const text = await response.text();
        const result = eval('(' + text + ')');

        if (result.status == 1) {
            return result.data;
        } else {
            return;
        }
    } catch (err) {
        throw err;
    }
}

// 分享E疗----上传相册
export async function uploadImages(media: any): Promise<{ loading: boolean; mediaArrays: any[] }> {
    let mediaArrays: any[] = [];
    let loading = true;
    return new Promise((resolve, reject) => {
        const pickedItems = Array.isArray(media) ? media : [media];
        Storage.getItem(RecordKeys.me).then((userInfo: any) => {
            userInfo = userInfo || {};
            const uploadPromises = pickedItems.map((item) => {
                const formData = new FormData();
                const file: any = {
                    uri: item.uri,
                    type: item.type,
                    name: item.fileName
                };
                formData.append('file', file);
                formData.append('armariumScienceSession', userInfo.token);
                return uploadImgApi(formData).then((res: any) => {
                    if (res.code === 200) {
                        mediaArrays.push(res.data);
                    } else {
                        throw new Error("Upload failed");
                    }
                });
            });
            Promise.all(uploadPromises)
                .then(() => {
                    loading = false;
                    resolve({ loading, mediaArrays });
                })
                .catch((error) => {
                    loading = false;
                    reject(error);
                });
        }).catch(reject);
    });
}

